package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.burgeon.backend.EnterpriseWeChat.service.EWBrandService;
import com.burgeon.backend.SHOPBACKEND.entity.dao.DaoMessage;
import com.burgeon.backend.SHOPBACKEND.entity.dao.WxMessage;
import com.burgeon.backend.SHOPBACKEND.entity.recored.MessageRecore;
import com.burgeon.backend.SHOPBACKEND.entity.vip.Vip;
import com.burgeon.backend.SHOPBACKEND.mappers.AndroidMapper;
import com.burgeon.backend.SHOPBACKEND.mappers.RecordMapper;
import com.burgeon.backend.SHOPBACKEND.rest.weixin.FindVipByOpenId;
import com.burgeon.backend.SHOPBACKEND.rest.weixin.ModVipUnread;
import com.burgeon.backend.SHOPBACKEND.rest.weixin.VipAppCode;
import com.burgeon.backend.SHOPBACKEND.service.RecordService;
import com.burgeon.backend.SHOPBACKEND.service.AWechatService;
import com.burgeon.backend.SHOPBACKEND.service.ex.UploadException;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class RecordServiceImpl implements RecordService {
    private static Logger log = LogManager.getLogger(RecordService.class);
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private AWechatService wechatService;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AndroidMapper androidMapper;

    @Override
    public List<MessageRecore> getRecord(String daoId, String openId,int page,String token) {
        if(null == daoId || daoId.isEmpty()){
            throw new UploadException("没有daoId");
        }else if(null ==openId || openId.isEmpty()) {
            throw new UploadException("没有openId");
        }
        Calendar calendar1 = Calendar.getInstance();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        calendar1.add(Calendar.DATE, -14);
        String endTime = sdf1.format(calendar1.getTime());
        String startTime = sdf1.format(new Date());
        int start = (page-1)*20;
        long sTime = System.currentTimeMillis();
        List<MessageRecore> messageRecores = recordMapper.getRecord(daoId,openId,startTime,endTime,start);
        Collections.reverse(messageRecores);
        System.err.println(messageRecores);
        long eTime = System.currentTimeMillis();
        long s= eTime-sTime;
        System.err.println("从数据库获取聊天记录时间"+s+"即"+s/(double)1000 + "秒");
        if(null != messageRecores){
           // wechatService.UpVipUnread(openId,"N");
//            long ssTime = System.currentTimeMillis();
            Info info = GetInfoByToken(token);
            FindVipByOpenId findVipByOpenId = new FindVipByOpenId(info.getUrl(),info.getAccount(),info.getPassword());
            ModVipUnread g = new ModVipUnread(info.getUrl(),info.getAccount(),info.getPassword());
//            long eeTime = System.currentTimeMillis();
//            long ss= eeTime-ssTime;
//            System.err.println("查询erp"+ss+"即"+ss/(double)1000 + "秒");
            try {
                Vip vip  = findVipByOpenId.getData(openId);

                    if("是".equals(vip.getUnread())) {

                    try {
                        g.getData(vip.getId(), "N");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {

                e.printStackTrace();
            }
            //修改数据库
            //upRecordState(daoId,openId);

            log.info("修改聊天记录为已读");
            return messageRecores;
        }
        //System.err.println("聊天记录"+messageRecores);
        return messageRecores;
    }

    @Override
    public List<MessageRecore> getAppRecord(String daoId, String openId, int page,String ip ) {
        if(null == daoId || daoId.isEmpty()){
            throw new UploadException("没有daoId");
        }else if(null ==openId || openId.isEmpty()) {
            throw new UploadException("没有openId");
        }
        String token = getAccount(ip);
        Calendar calendar1 = Calendar.getInstance();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        calendar1.add(Calendar.DATE, -14);
        String endTime = sdf1.format(calendar1.getTime());
        String startTime = sdf1.format(new Date());
        int start = (page-1)*20;
        long sTime = System.currentTimeMillis();
        List<MessageRecore> messageRecores = recordMapper.getRecord(daoId,openId,startTime,endTime,start);
        long eTime = System.currentTimeMillis();
        long s= eTime-sTime;
        System.err.println("从数据库获取聊天记录时间"+s+"即"+s/(double)1000 + "秒");
        if(null != messageRecores){
            // wechatService.UpVipUnread(openId,"N");
//            long ssTime = System.currentTimeMillis();
            Info info = GetInfoByToken(token);
            FindVipByOpenId findVipByOpenId = new FindVipByOpenId(info.getUrl(),info.getAccount(),info.getPassword());
            ModVipUnread g = new ModVipUnread(info.getUrl(),info.getAccount(),info.getPassword());
//            long eeTime = System.currentTimeMillis();
//            long ss= eeTime-ssTime;
//            System.err.println("查询erp"+ss+"即"+ss/(double)1000 + "秒");
            try {
                Vip vip  = findVipByOpenId.getData(openId);

                if("是".equals(vip.getUnread())) {

                    try {
                        g.getData(vip.getId(), "N");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {

                e.printStackTrace();
            }
            //修改数据库
            //upRecordState(daoId,openId);

            log.info("修改聊天记录为已读");
            return messageRecores;
        }
        //System.err.println("聊天记录"+messageRecores);
        return messageRecores;
    }
    public String getAccount(String url){
        System.err.println("IP穿"+url);
        String token = androidMapper.GetTokenByUrl(url);
        System.err.println(token);
        String account = androidMapper.GetTokenByToken(token);
        System.err.println(account);
        return account;

    }
    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }

    /**
     * 修改未读消息
     * @param daoId
     * @return
     */
    @Override
    public Integer upRecordState(String daoId,String openId) {
        //1.查询未读消息
        List<MessageRecore> messageRecores = recordMapper.getRecordByState(daoId,openId);

        System.err.println("未读消息"+messageRecores);

        //有未读消息
        if(messageRecores != null) {

            for (MessageRecore mr : messageRecores) {
                //2.修改未读消息
                Integer r = recordMapper.upRecordState(mr.getId(), "0");
                //失败的情况
//                if (r == 0) {
//                    System.err.println(r);
//                    log.info("修改未读消息状态失败");
//                }

                //3.修改erp的是否有未读消息状态为“N”
               // wechatService.UpVipUnread(openId,"N");

                log.info("修改为已读");
            }

        }

        return null;
    }

    @Override
    public Boolean getLastRecord(String openId) {
        String last = recordMapper.getLastRecord(openId);
        System.err.println(""+last);
        Date now = new Date();
        boolean state = false;
        try {
            if (null != last){
                state = judgmentDate(last,now);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new UploadException("是否超过48小时"+e.getMessage());
        }
        return state;
    }
    /**判断是否超过24小时
     *
     * @param date1
     * @param date2
     * @return boolean
     * @throws Exception
     */

    public static boolean judgmentDate(String date1, Date date2) throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date start = sdf.parse(date1);

        long cha = date2.getTime() - start.getTime();

        if(cha<0){
            return false;
        }

        double result = cha * 1.0 / (1000 * 60 * 60);

        if(result<=48){

            return true;

        }else{

            return false;

        }

    }


    //根据openid查询聊天信息纪录
    @Override
    public List<WxMessage> getWxRecord(String openId, String daoId) {
        //获取微信用户的聊天记录
       List<WxMessage> wxMessages = recordMapper.getWxRecord(openId);

        //获取安卓发送给微信的聊天记录
       // recordMapper.getDaoRecord(openId,daoId);

        return wxMessages;
    }

    //导购发送给微信的信息
    @Override
    public List<DaoMessage> getDaoRecord(String openId, String daoId) {
        List<DaoMessage> daoMessages = recordMapper.getDaoRecord(openId,daoId);
        return daoMessages;
    }

    //查询导购没有连接，微信用户没有成功发送的消息
    @Override
    public List<WxMessage> getWxRecordBysState(String openId) {
        return recordMapper.getWxRecordBysState(openId);
    }
}
